
//  RBGoodsDetailViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/5/16.
//  Copyright © 2018年 Tzyang. All rights reserved.
//  商品详情控制器 (推荐商品 和秒杀商品的区别 秒杀商品有一个时间)

#import "RBGoodsDetailViewController.h"
#import "XJSureOrderViewController.h" // 6-11 确认订单
#import "XJGoodsAllEvaluateViewController.h" // 7-10 全部评论


//view
#import "RBGoodsDetailHeaderView.h"
#import "RBGoodsDetailFootView.h"
#import "RBGoodsTransportFeeTableViewCell.h"
#import "RBGoodsSelectGuiGeTableViewCell.h"
#import "RBTransportRuleView.h"
#import "XJSelectStandardsView.h"
#import "XJShangPinEvaluateCell.h" // 6-11 商品评价
#import "XJShangPinEvaluateSectionHeaderView.h" // 6-11商品评价区头

//vendor
#import <UShareUI/UShareUI.h>


// model
#import "XJGoodsDetailModel.h"
#import "XJFeatureSectionItemModel.h"
#import "XJStockModel.h" // 比对库存数组
#import "XJShangPinEvaluateModel.h" // 6-11 商品评价model

// tool
#import "LMJUMengHelper.h"
#import "XJUserModel.h"

//Controller
#import "XJLoginViewController.h"
#import "XJShopDetailViewController.h" // 店铺详情



@interface RBGoodsDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) RBGoodsDetailHeaderView *headerView;
@property(nonatomic, strong) RBGoodsDetailFootView *footerView;
@property(nonatomic, strong) XJSelectStandardsView *selStandardsV;
@property(nonatomic, strong) RBTransportRuleView *transportRuleV;

@property(nonatomic, strong) XJGoodsDetailModel *goodsDetailModel;

// 数据源
/**选择规格最层大数组*/
@property(nonatomic, strong) NSMutableArray *bigArr;
/**用于判断库存的数组*/
@property(nonatomic, strong) NSMutableArray *stockArr;

/**5-21选择规格后的购买信息字典 在selStandardsV 的确定按钮回调的地方赋值*/
@property(nonatomic, strong) NSDictionary *chosenInfoDic;

/**6-11商品评价cell的数据源*/
@property (nonatomic, strong) NSMutableArray *evaluateArray;

@end

@implementation RBGoodsDetailViewController

#pragma mark - 一 lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        [_tableView registerNib:[UINib nibWithNibName:@"RBGoodsTransportFeeTableViewCell" bundle:nil] forCellReuseIdentifier:@"RBGoodsTransportFeeTableViewCell"];//运费cell
        [_tableView registerNib:[UINib nibWithNibName:@"RBGoodsSelectGuiGeTableViewCell" bundle:nil] forCellReuseIdentifier:@"RBGoodsSelectGuiGeTableViewCell"];
        
        
         [_tableView registerNib:[UINib nibWithNibName:@"XJShangPinEvaluateCell" bundle:nil] forCellReuseIdentifier:@"XJShangPinEvaluateCell"]; // 6-11
        [_tableView registerClass:[XJShangPinEvaluateSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"XJShangPinEvaluateSectionHeaderView"]; // 6-11 商品评价区头
        
        _tableView.tableFooterView = [[UIView alloc] init];
    }
    return _tableView;
}

- (RBGoodsDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[RBGoodsDetailHeaderView alloc] init];
    }
    return _headerView;
}
- (RBGoodsDetailFootView *)footerView {
    if (!_footerView) {
        _footerView = [[RBGoodsDetailFootView alloc] init];
        
        
        XJWeakSelf(self);
        // 回调
        _footerView.clickStoreBlock = ^{

            NSString *shopId = weakself.goodsDetailModel.shop_id;
            XJLog(@"店铺:%@",shopId);

            if ([NSString isEmptyString:shopId]) {
                [MBProgressHUD showError:@"shopId 参数不能为空"];
                return ;
            }
            XJShopDetailViewController *shopDetailVC = [[XJShopDetailViewController alloc] init];
            shopDetailVC.shopId = shopId;
            [weakself.navigationController pushViewController:shopDetailVC animated:YES];
            
        };
        _footerView.clickKeFuBlock = ^{
            XJLog(@"客服");
        };
        
        //收藏
        _footerView.clickStarBlock = ^(BOOL isSelectBtn) {
            XJLog(@"%@",isSelectBtn?@"收藏":@"取消");
            
            NSString * goodsIdStr = weakself.goodsDetailModel.goodsId;
            if (isSelectBtn) { //调取消收藏的接口
                [weakself requestShouchangGoodsWithGoodId:goodsIdStr];
            }else { //调收藏的接口
                [weakself requestCancelShoucangGoodsWithGoodId:goodsIdStr];
            }
        };
        
        _footerView.clickAddShopcartBlock = ^{
//            XJLog(@"添加到购物车");
            [weakself clickAddToShopcartAction];
        };
        _footerView.clickBuynowBlock = ^{
            
            [weakself clickBuyNowAction];

        };
    }
    return _footerView;
}

- (XJSelectStandardsView *)selStandardsV {
    if (!_selStandardsV) {
        _selStandardsV = [XJSelectStandardsView new];
    
        XJWeakSelf(self)
        self.selStandardsV.clickSureBtnBlock = ^(NSDictionary *choseGoodsInfoDic, XJSelectStandardsViewBuyType type) {
            
            weakself.chosenInfoDic = choseGoodsInfoDic;

            if (type == XJSelectStandardsViewXZGJType) { //从选择规格进去的
                XJLog(@"从选择规格中进去的");
            }else if (type == XJSelectStandardsViewAddCartType) { //从加入购物车进去的
                XJLog(@"从加入购物车进去的");
                [weakself clickAddToShopcartAction];
            }else if(type == XJSelectStandardsViewBuyNowType) { //从立即购买进去的
                XJLog(@"从立即购买进去的");
                [weakself clickBuyNowAction];
            }else {
                XJLog(@"未知情况不做处理");
            }
        };
    }
    return _selStandardsV;
}
- (RBTransportRuleView *)transportRuleV {
    if (!_transportRuleV) {
        _transportRuleV = [[RBTransportRuleView alloc] init];
    }
    return _transportRuleV;
}

- (NSMutableArray *)bigArr {
    if (!_bigArr) {
        _bigArr = [NSMutableArray array];
    }
    return _bigArr;
}

- (NSMutableArray *)stockArr {
    if (!_stockArr) {
        _stockArr = [NSMutableArray array];
    }
    return _stockArr;
}

#pragma mark - 二 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self requestGoodsInfo];

    [self setupNav];
    
    [self setupUI];
}



- (void)setupNav {
//    UIButton *shareBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
//    [shareBtn setImage:[UIImage imageNamed:@"nav_share"] forState:(UIControlStateNormal)];
//    shareBtn.size = CGSizeMake(30, 30);
//    [shareBtn addTarget:self action:@selector(clickShareAction) forControlEvents:(UIControlEventTouchUpInside)];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:shareBtn];
    
//    UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 40)];
//    redView.backgroundColor = [UIColor redColor];
//    self.navigationItem.titleView = redView;
//    self.navigationItem.title = @"商品详情";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_share"] style:(UIBarButtonItemStylePlain) target:self action:@selector(clickShareAction)];
}

- (void)clickShareAction {
    XJLog(@"分享");
    [self showMiddleNormalView];
}

- (void)showMiddleNormalView
{
    [UMSocialShareUIConfig shareInstance].sharePageGroupViewConfig.sharePageGroupViewPostionType = UMSocialSharePageGroupViewPositionType_Middle;
    
    [LMJUMengHelper shareTitle:@"新疆商城" subTitle:@"谢谢使用!欢迎交流!" thumbImage:@"https://avatars2.githubusercontent.com/u/18454795?s=400&u=c8a7cc691e5c3611e9fb49dcf9c83843dd9141a2&v=4" shareURL:@"https://www.github.com/njhu"];
}

- (NSMutableArray *)evaluateArray {
    if (!_evaluateArray) {
        _evaluateArray = [NSMutableArray array];
    }
    return _evaluateArray;
}

- (void)setupUI {
    self.tableView.frame = CGRectMake(0, 0, KWidth, KHeight-XJTopNavH - ADAPTHeight(50));
    [self.view addSubview:self.tableView];

    // 设置表头 375+60
    self.headerView.frame = CGRectMake(0, 0, KWidth, ADAPTHeight(435));
    self.tableView.tableHeaderView = self.headerView;

    //底部 "店铺 客服 收藏 加入购物车 立即购买" 控件
    self.footerView.frame = CGRectMake(0, KHeight - ADAPTHeight(50) - XJTopNavH , KWidth, ADAPTHeight(50));
    [self.view addSubview:self.footerView];
}

#pragma mark - 三 获取数据
- (void)requestGoodsInfo {
    [XJHttpTool requestGoodsInfo:self.goodsId successHandler:^(id responseObjc) {
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        XJLog(@"商品详情:%@",jsonStr);
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) { // 正确返回数据
            NSDictionary *goods_infoDic = responseObjc[@"data"][@"goods_info"];
            
            // 一:商品详情model数据
            XJGoodsDetailModel *model = [XJGoodsDetailModel mj_objectWithKeyValues:goods_infoDic[@"goods"]];
            // 单独赋值
            model.is_collection = goods_infoDic[@"is_collection"];
            model.express = goods_infoDic[@"express"];
            self.goodsDetailModel = model;
            
            // 二:库存数组
            NSArray *tmpStockArr = responseObjc[@"data"][@"goods_info"][@"goods_options"];
            if (tmpStockArr.count) {
                for (NSDictionary *tmpDic in tmpStockArr) {
                    XJStockModel *stockM = [XJStockModel mj_objectWithKeyValues:tmpDic];
                    [self.stockArr addObject:stockM];
                }
            }
            
            
            // 四: 商品评论数组:返回的就是一个字典。还是用数组装吧
            NSDictionary *commentDic = responseObjc[@"data"][@"goods_info"][@"comment"];
            XJLog(@"%@",commentDic);
            if ([commentDic isKindOfClass:[NSNull class]]) { // null
                XJLog(@"字典为空 不做处理");
            }else {
                XJShangPinEvaluateModel *evaluteM = [XJShangPinEvaluateModel mj_objectWithKeyValues:commentDic];
                [self.evaluateArray addObject:evaluteM];
            }
            
            // 三:选择规格最外层大数组:两种情况:有规格、没规格(没有做处理)
            NSArray *tmpBigArr = responseObjc[@"data"][@"goods_info"][@"spec"];
            // 防止数组为空奔溃
            if (tmpBigArr.count) {
                self.bigArr = [XJFeatureSectionItemModel mj_objectArrayWithKeyValuesArray:tmpBigArr];
            }
            
            // 只有数据的时候 才进行处理
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.headerView configRBGoodsDetailHeaderViewImages:model.imagesArray name:model.name price:model.price originPrice:model.market_price payCount:model.pay_count];
                self.footerView.isStar = [model.is_collection integerValue];
                
                [self.tableView reloadData];
            });
            
        }else { // 没有正确返回数据
            [JRToast showWithText:responseObjc[@"message"]];
        }
        
    } failureHandler:^(NSError *error) {
        XJLog(@"商品详情 失败");
        [MBProgressHUD showError:[error localizedDescription]];
    }];
}

#pragma mark - 模拟数据 显示选择规格view
- (NSMutableArray *)moniDataArr {
    NSArray *tempArr = @[ @{ @"name":@"重量",@"items":@[@{@"name":@"80g",@"guigeId":@"137"},@{@"name":@"100g",@"guigeId":@"138"},@{@"name":@"150g",@"guigeId":@"139"}                                         ]
                            },
                          @{@"name":@"颜色",
                            @"items":@[@{@"name":@"蓝色",@"guigeId":@"140"},
                                         @{@"name":@"绿色",@"guigeId":@"141"},
                                         @{@"name":@"紫色",@"guigeId":@"142"}
                                         ]
                            }
                          ];
    
    NSMutableArray *newArr = [NSMutableArray array];
    
    for (NSDictionary *dic in tempArr) {
        XJFeatureSectionItemModel *bigM = [XJFeatureSectionItemModel mj_objectWithKeyValues:dic];
        [newArr addObject:bigM];
    }
    
    return newArr.copy;
}
//模拟库存数组
- (NSArray *)moniStockArr {
    NSArray *tempArr = @[@{@"stock":@"100",@"specs":@"137_140",@"id":@"102"},
             @{@"stock":@"120",@"specs":@"137_141",@"id":@"103"},
             @{@"stock":@"80",@"specs":@"137_142",@"id":@"104"},
             @{@"stock":@"23",@"specs":@"138_140",@"id":@"105"},
             @{@"stock":@"45",@"specs":@"138_141",@"id":@"106"},
             @{@"stock":@"78",@"specs":@"138_142",@"id":@"107"},
             @{@"stock":@"11",@"specs":@"139_140",@"id":@"108"},
             @{@"stock":@"92",@"specs":@"139_141",@"id":@"109"},
             @{@"stock":@"22",@"specs":@"139_142",@"id":@"110"},
             ];
    
    NSMutableArray *newArr = [NSMutableArray array];
    for (NSDictionary *dic in tempArr) {
        XJStockModel *model = [XJStockModel mj_objectWithKeyValues:dic];
        [newArr addObject:model];
    }
    
    return newArr.copy;
}

#pragma mark  - 四  UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // 运费cell+选择规格cell+商品评价+图文详情 (4)
    if (section==0) {
        return 2;
    }else if (section == 1){
        // 如果数组有值:就显示一个cell。 没有就不显示
        if (self.evaluateArray.count) {
            return 1;
        }else {
            return 0;
        }
    }else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) { //运费
            RBGoodsTransportFeeTableViewCell *transpotrFeeCell = [tableView dequeueReusableCellWithIdentifier:@"RBGoodsTransportFeeTableViewCell"];
            [transpotrFeeCell configTransportFee:self.goodsDetailModel.dispatch_fee];
            
            return transpotrFeeCell;
        } else {
            RBGoodsSelectGuiGeTableViewCell *guigeCell = [tableView dequeueReusableCellWithIdentifier:@"RBGoodsSelectGuiGeTableViewCell"];
            return guigeCell;
        }
        
    }else if (indexPath.section == 1) {
        
        // 商品评价
        XJShangPinEvaluateCell *evaluateCell = [tableView dequeueReusableCellWithIdentifier:@"XJShangPinEvaluateCell"];
        
        evaluateCell.evaluateM = [self.evaluateArray firstObject];
        return evaluateCell;
    }else {
        
        UITableViewCell *cell = [[UITableViewCell alloc] init];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.text = @"图文详情";
        return cell;
    }
}


#pragma mark -  UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 44;
    }else if (indexPath.section == 1) {
        return 120;
    }else {
        return 100;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) { // 0.运费规则
            //        XJLog(@"运费规则");
            [self clickTransportRuleAction];
        }else if (indexPath.row == 1) { // 1.选择套餐、规格
            XJLog(@"套餐规格");
            [self xuanzeguigeWithBuyType:(XJSelectStandardsViewXZGJType)];
        }
    }else if(indexPath.section == 1) { // 商品评价
        XJLog(@"点击商品评价");
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 1) {
        XJShangPinEvaluateSectionHeaderView *evaluateSectionHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"XJShangPinEvaluateSectionHeaderView"];
        
        [evaluateSectionHeaderView configureShangPinEvaluateSectionHeaderViewWithPraise_rate:self.goodsDetailModel.praise_rate comment_count:self.goodsDetailModel.comment_count];
        
        evaluateSectionHeaderView.xjsppjSecHeadViewClickAllEvluteBlock = ^{
            
            XJGoodsAllEvaluateViewController *goodAllEvVC = [XJGoodsAllEvaluateViewController new];
            goodAllEvVC.navTitle = [NSString stringWithFormat:@"全部评论(%@)",self.goodsDetailModel.comment_count];
            
            goodAllEvVC.goodID = [NSString stringWithFormat:@"%@",self.goodsId];
            
              [self.navigationController pushViewController:goodAllEvVC animated:YES];
        };
        return evaluateSectionHeaderView;
    }else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 44;
    }else {
        return 0;
    }
}


#pragma mark - 五  点击事件方法
- (void)clickTransportRuleAction {
    [self.transportRuleV rb_showInView:self.view ruleStr:self.goodsDetailModel.express];
}


- (void)clickAddToShopcartAction {
    XJLog(@"添加到购物车");
    //如果 self.chosenInfoDic 为空,跳转选择规格界面。反之调用接口添加到购物车
    
    if (self.chosenInfoDic) {
        [self requestAddShopcart:self.chosenInfoDic];
    }else {
        [self xuanzeguigeWithBuyType:(XJSelectStandardsViewAddCartType)];
    }
}
- (void)clickBuyNowAction {
    XJLog(@"立即购买");
    // 1.先判断是否已经登录
    // 2.是否选择了规格了 、 没选就去选择规格
    // 3.选了规格----> 调接口
    if ([XJUserModel xj_isLogin]) {
        
        // chosenInfoDic
        XJLog(@"%@",self.chosenInfoDic);
        if (self.chosenInfoDic == nil || self.chosenInfoDic == NULL) {
            XJLog(@"字典是空的--->选择规格:");
            
            [self xuanzeguigeWithBuyType:(XJSelectStandardsViewBuyNowType)];
            return;
        }
       
        // 调接口
//        [self requestBuyNowWithDic:self.chosenInfoDic];
        
        XJSureOrderViewController *sureOrderVC = [[XJSureOrderViewController alloc] init];
        sureOrderVC.comeFromVC = XJComeFromTypeRBGoodsDetailViewController;
        
        sureOrderVC.parDic = self.chosenInfoDic; //6-12
        [self.navigationController pushViewController:sureOrderVC animated:YES];
        
    }else{
        //去登陆
        XJLoginViewController *loginVC = [[XJLoginViewController alloc] init];
        [self presentViewController:loginVC animated:YES completion:nil];
    }
}
#pragma mark - 六 接口调用
- (void)requestAddShopcart:(NSDictionary *)dic {
    [XJHttpTool requestAddCartDic:dic successH:^(id responseObjc) {
        XJLog(@"加入成功:%@",responseObjc);
        if ([responseObjc[@"code"] isEqualToNumber:@0]) {
            [MBProgressHUD showSuccess:@"加入购物车成功"];
        }else {
            [MBProgressHUD showError:responseObjc[@"message"]];
        }
        
    } failureH:^(NSError *error) {
        XJLog(@"失败:%@",error);
        [MBProgressHUD showError:[error localizedDescription]];
    }];
}

- (void)requestBuyNowWithDic:(NSDictionary *)dic{
    
    [XJHttpTool requestBuyNowWithDic:dic successH:^(id responseObjc) {
        
        XJLog(@"%@",responseObjc);

        NSNumber *code = responseObjc[@"code"];
        if ([code isEqualToNumber:@0]) {
            // 跳转界面;
            
            
           
            
            // 是否有收货地址:有直接下单
            // 没有:跳转选择收货地址。
        
            NSDictionary *address = responseObjc[@"address"];
            if (address == nil || address ==NULL) {
                // 跳转:选择收货地址。
                XJLog(@"没有收货地址");
                return ;
            }
            
            // 接下来的操作。
        }else{
            [MBProgressHUD showError:responseObjc[@"message"]];
        }
        
    } failH:^(NSError *error) {
        XJLog(@"%@",error);
    }];
}



- (void)requestShouchangGoodsWithGoodId:(NSString *)goodId{
    XJLog(@"收藏");
    [MBProgressHUD showMessage:@""];

    [XJHttpTool requestAddShouCangWithGoods_id:goodId successH:^(id responseObjc) {
        if ([responseObjc[@"code"] isEqualToNumber:@0]) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showSuccess:@"收藏成功"];
//            weakself.footerView.isStar = YES;
        }else {
            [MBProgressHUD showError:responseObjc[@"message"]];
        }
    } failH:^(NSError *error) {
        NSLog(@"成功:%@",error);
        [MBProgressHUD showError:[error localizedDescription]];
    }];
}

- (void)requestCancelShoucangGoodsWithGoodId:(NSString *)goodId {
    XJLog(@"取消收藏");
    [MBProgressHUD showMessage:@""];

    [XJHttpTool requestCancelShouCangGoodsWithGoodsId:goodId successH:^(id responseObjc) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showSuccess:@"取消成功"];

        if ([responseObjc[@"code"] isEqualToNumber:@0]) {
            //            weakself.footerView.isStar = YES;
        }else {
            [MBProgressHUD showError:responseObjc[@"message"]];
        }
    } fail:^(NSError *error) {
        [MBProgressHUD showError:[error localizedDescription]];
    }];
   
}

#pragma mark - 七 private method
- (void)xuanzeguigeWithBuyType:(XJSelectStandardsViewBuyType)type {
    if (self.bigArr.count && self.stockArr.count) {
        self.selStandardsV.dataArr = self.bigArr;
        self.selStandardsV.stockArr = self.stockArr;
    }else {//如果服务器返回空数组就用 假数据
//        self.selStandardsV.dataArr = [self moniDataArr];
//        self.selStandardsV.stockArr = [self moniStockArr];
    }
    
    // 防空 判断
    if ([NSString isEmptyString:self.goodsDetailModel.cover] || [NSString isEmptyString:self.goodsDetailModel.price] || [NSString isEmptyString:self.goodsDetailModel.goodsId] || [NSString isEmptyString:self.goodsDetailModel.shop_id]) {
        XJLog(@"有字段为空 ,操作无效");
        return;
    }
    
    self.selStandardsV.buyInfoDic = @{@"cover":self.goodsDetailModel.cover,
                                      @"price":self.goodsDetailModel.price,
                                      @"goodsId":self.goodsDetailModel.goodsId,
                                      @"shop_id":self.goodsDetailModel.shop_id
                                      };
    [self.selStandardsV rb_showSelectStandardsViewWithType:type];
}

@end
